<template>
  <div class="test-paper">
    <div class="print-area">
      <div class="header">
        <h2>{{ testPaper.title }}</h2>
        <p>{{ testPaper.description }}</p>
        <div class="paper-info">
          <span>总分: {{ testPaper.total_score }} 分</span>
          <span v-if="testPaper.time_limit">时间限制: {{ testPaper.time_limit }} 分钟</span>
        </div>
      </div>

      <div class="questions">
        <div 
          v-for="(question, index) in testPaper.questions" 
          :key="question.id" 
          class="question-item"
        >
          <div class="question-header">
            <span class="question-number">第 {{ index + 1 }} 题 ({{ getQuestionTypeName(question.type) }})</span>
            <span class="question-score">{{ question.score }} 分</span>
          </div>
          
          <div class="question-content" v-html="formatQuestionContent(getStemContent(question))"></div>
          
          <div class="question-options" v-if="question.type === 'choice'">
            <el-radio-group v-model="userAnswers[question.id]">
              <el-radio 
                v-for="(option, optIndex) in displayOptions(question)" 
                :key="optIndex" 
                :label="String.fromCharCode(65 + optIndex)"
                class="option-item"
              >
                {{ String.fromCharCode(65 + optIndex) }}.{{ option }}
              </el-radio>
            </el-radio-group>
          </div>
          
          <div class="question-answer" v-else>
            <el-input
              v-model="userAnswers[question.id]"
              :placeholder="getAnswerPlaceholder(question.type)"
              :type="question.type === 'solve' ? 'textarea' : 'text'"
              :rows="question.type === 'solve' ? 3 : 1"
            />
          </div>
        </div>
      </div>
    </div>

    <div class="actions">
      <el-button type="primary" @click="submitPaper" :loading="submitting">
        提交试卷
      </el-button>
      <el-button @click="printPaper">打印</el-button>
      <el-button @click="downloadPaper">下载</el-button>
      <el-button @click="$emit('back')">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

interface Question {
  id: number
  content: string
  type: string
  options?: string[]
  score: number
}

interface TestPaper {
  id: number
  title: string
  description?: string
  total_score: number
  time_limit?: number
  questions: Question[]
}

const props = defineProps<{
  testPaper: TestPaper
}>()

const emit = defineEmits<{
  (e: 'submit', answers: Record<number, string>): void
  (e: 'back'): void
}>()

const submitting = ref(false)
const userAnswers = reactive<Record<number, string>>({})

const getQuestionTypeName = (type: string) => {
  const typeNames: Record<string, string> = {
    choice: '选择题',
    fill: '填空题',
    solve: '解答题'
  }
  return typeNames[type] || type
}

const getAnswerPlaceholder = (type: string) => {
  const placeholders: Record<string, string> = {
    choice: '请选择答案',
    fill: '请输入答案',
    solve: '请详细解答'
  }
  return placeholders[type] || '请输入答案'
}

const formatQuestionContent = (content: string) => {
  return content.replace(/\n/g, '<br>')
}

const parseOptionsFromContent = (content: string): string[] => {
  const lines = content.split(/\r?\n/)
  const opts: string[] = []
  for (const line of lines) {
    const m = line.match(/^([A-D])[\.|\)]\s*(.*)$/)
    if (m) opts.push(m[2].trim())
  }
  return opts
}

const getStemContent = (q: Question) => {
  if (q.type !== 'choice') return q.content
  const lines = q.content.split(/\r?\n/)
  const stem: string[] = []
  for (const line of lines) {
    if (/^[A-D][\.|\)]\s*/.test(line)) break
    stem.push(line)
  }
  return stem.join('\n')
}

const displayOptions = (q: Question): string[] => {
  let opts: string[] = []
  if (q.options && q.options.length) opts = q.options.slice(0, 4)
  else {
    const parsed = parseOptionsFromContent(q.content)
    opts = parsed.slice(0, 4)
  }
  opts = opts.map(o => (o ?? '').trim())
  while (opts.length < 4) opts.push('')
  return opts
}

const printPaper = () => {
  window.print()
}

const downloadPaper = async () => {
  const el = document.querySelector('.print-area') as HTMLElement
  if (!el) return
  const canvas = await html2canvas(el, { scale: 2, useCORS: true })
  const imgData = canvas.toDataURL('image/png')
  const pdf = new jsPDF('p', 'pt', 'a4')
  const pageWidth = pdf.internal.pageSize.getWidth()
  const pageHeight = pdf.internal.pageSize.getHeight()
  const imgWidth = pageWidth
  const imgHeight = canvas.height * (imgWidth / canvas.width)

  let position = 0
  if (imgHeight <= pageHeight) {
    pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight)
  } else {
    while (position < imgHeight) {
      pdf.addImage(imgData, 'PNG', 0, -position, imgWidth, imgHeight)
      position += pageHeight
      if (position < imgHeight) pdf.addPage()
    }
  }
  pdf.save(`${props.testPaper.title}.pdf`)
}

const submitPaper = () => {
  // 检查是否所有题目都已回答
  const unanswered = props.testPaper.questions.filter(q => !userAnswers[q.id])
  
  if (unanswered.length > 0) {
    ElMessage.warning(`还有 ${unanswered.length} 题未完成`)
    return
  }
  
  submitting.value = true
  emit('submit', { ...userAnswers })
  submitting.value = false
}
</script>

<style scoped>
.test-paper {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.paper-info {
  margin-top: 10px;
}

.paper-info span {
  margin-right: 20px;
  color: #666;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e6e8eb;
  border-radius: 8px;
  background: white;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.question-number {
  font-weight: bold;
  color: #333;
}

.question-score {
  color: #67c23a;
  font-weight: bold;
}

.question-content {
  margin-bottom: 15px;
  line-height: 1.6;
  color: #333;
}

.option-item {
  display: block;
  margin: 8px 0;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.option-item:hover {
  background-color: #f5f7fa;
}

.actions {
  text-align: center;
  margin-top: 40px;
  padding: 20px;
}

.actions .el-button {
  margin: 0 10px;
}
</style>